package Web_Helper;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


import javax.mail.PasswordAuthentication;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 *
 * @author Randall Chia
 */

//Used to send emails via SMTP with Gmail host 

public class EmailSender {

    private String senderEmail;
    private String senderPassword;

    public EmailSender() {
    }

    public EmailSender(String senderEmail, String senderPassword) {
        this.senderEmail = senderEmail;
        this.senderPassword = senderPassword;
    }

    public void postMail(String recipients[], String subject, String message, String from) throws MessagingException {


        //Set the host smtp address
        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.debug", "true");


        Authenticator auth = new SMTPAuthenticator(senderEmail, senderPassword);
        Session session = Session.getInstance(props, auth);
        session.setDebug(true);


        // create a message
        Message msg = new MimeMessage(session);

        // Setting the message sender
        InternetAddress addressFrom = new InternetAddress(from);
        msg.setFrom(addressFrom);

        // Setting the message recipients
        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            addressTo[i] = new InternetAddress(recipients[i]);
        }
        msg.setRecipients(Message.RecipientType.TO, addressTo);

        // Setting the Subject and Content Type
        msg.setSubject(subject);
        msg.setContent(message, "text/plain");
        Transport.send(msg);
    }
    
    //Nested class, used to handle authentications
    protected class SMTPAuthenticator extends javax.mail.Authenticator {
 	private String username;
 	private String password;
 	
 	
 	public SMTPAuthenticator(){}
 	
 	
 	public SMTPAuthenticator(String username, String password){	
 		this.username = username;
 		this.password = password;
 	}

        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(senderEmail, senderPassword);
        }
    }
}